<template>
	<div class="web-footer-container" id="web-footer">
		<div class="emoji-wrapper" v-show="showEmoji">
			<Emoji @addEmoji="addEmoji"></Emoji>
		</div>
		<div class="web-footer-header">
			<div class="web-footer-tool-box">
				<img src="../../assets/img/sendEmoji.png" alt="" srcset="" width="20px" @click="selectEmoji($event)" />
				<img v-if="!hideImageButton"  src="../../assets/img/sendImage.png" alt="" srcset="" width="20px" onclick="document.getElementById('imgfile').click()" />
				<input style="display: none" type="file" name="file" id="imgfile" value="" accept="image/gif,image/jpg,image/jpeg,image/png" @change="sendImage($event)" />
				<img v-if="!hideFileButton" src="../../assets/img/sendFile.png" alt="" srcset="" width="20px" onclick="document.getElementById('docfile').click()" />
				<input style="display: none" type="file" name="docfile" id="docfile" value="" @change="sendFile($event)" />
				<img v-if="showKbButton" src="../../assets/img/knowledge-base.png" alt="" srcset="" width="20px" @click="handleKnowledgeBase" />
			</div>
			<div class="send-btn-box">
				<button>
					<span @click="sendMessageText">{{ $t('send') }}</span>
					<img src="../../assets/img/dropDown.png" alt="" srcset="" @click="setNormalWordView($event)" />
				</button>
			</div>
		</div>
		<div class="web-chat-window-footer">
			<div
				contenteditable="plaintext-only"
				suppressContentEditableWarning
				@keydown="keyDown"
				:placeholder="$t('enter-content')"
				spellCheck
				id="widget-message-text"
				class="widget-message-text"
				ref="inputRef"
			>
			</div>
			<!-- <div
				@focus="inputFocus($event)"
				placeholder="请输入聊天内容..."
				
				id="widget-message-text"
				class="widget-message-text"
				@keydown="keyDown"
				contenteditable="plaintext-only"
			></div> -->
		</div>
		<NormalWord v-if="showNormalWordView" />
	</div>
</template>

<script>
import Emoji from '../Emoji';
import NormalWord from '@/components/ChatMessage/NormalWord.vue';
import { sendMessageToRecord } from '../../utils/message';
import zcoIMEvent from '@/store/event';
import { getSelection, updateCaret } from '../../utils/contentEditable';
import ZcoIM from '../../index';
export default {
	components: { NormalWord, Emoji },
	props: {
		hideImageButton: {
			type: Boolean,
			default: false
		},
		hideFileButton: {
			type: Boolean,
			default: false
		},
		showKbButton: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			showNormalWordView: false,
			showEmoji: false,
		};
	},
	mounted() {
		document.body.addEventListener('click', () => {
			if (this.showNormalWordView) {
				this.showNormalWordView = !this.showNormalWordView;
			}
		});
		this.$nextTick(() => {
			this.initSelection();
		});
	},
	methods: {
		initSelection() {
			this.$refs.inputRef.onclick = () => {
				// 获取选定对象
				var selection = window.getSelection();
				// 设置最后光标对象
				this.lastEditRange = selection.getRangeAt(0);
			};

			// 编辑框按键弹起事件
			this.$refs.inputRef.onkeyup = () => {
				// 获取选定对象
				var selection = window.getSelection();
				// 设置最后光标对象
				this.lastEditRange = selection.getRangeAt(0);
			};

			// 失去焦点事件
			this.$refs.inputRef.onblur = () => {
				// 获取选定对象
				var selection = window.getSelection();
				// 设置最后光标对象
				this.lastEditRange = selection.getRangeAt(0);
			};
		},
		/**
		 * 监听图片粘贴事件
		 */
		initPaste() {
			document.addEventListener('paste', event => {
				let items = event.clipboardData && event.clipboardData.items;
				// let url = window.URL || window.webkitURL;
				let file = null;
				if (items && items.length) {
					// 检索剪切板items
					for (let i = 0; i < items.length; i++) {
						if (items[i].type.indexOf('image') !== -1) {
							file = items[i].getAsFile();
							break;
						}
					}
				}
				if (file) {
					console.log(file);
					// upload file
					this.handleImgUpload(file);
				}
			});
		},
		/**
		 * 添加emoji到input
		 */
		addEmoji(emoji) {
			const el = this.$refs.inputRef;
			if (!this.lastEditRange) {
				el.focus();
				var selection = window.getSelection();
				// 设置最后光标对象
				this.lastEditRange = selection.getRangeAt(0);
			}
			const { start, end } = getSelection(el, this.lastEditRange);
			if (el.innerHTML) {
				const firstPart = el.innerHTML.substring(0, start);
				const secondPart = el.innerHTML.substring(end);
				console.log(firstPart, secondPart);
				el.innerHTML = `${firstPart}${emoji}${secondPart}`;
			} else {
				el.innerHTML = emoji;
			}
			updateCaret(el, start, emoji.length, this.lastEditRange);
		},
		inputFocus(e) {
			console.log('zco-web-footer-focus', e, new Date());
		},
		//回车键发送消息
		keyDown(event) {
			if (!event.shiftKey && event.keyCode == 13) {
				event.cancelBubble = true;
				event.preventDefault();
				event.stopPropagation();
				this.sendMessageText();
			}
		},
		// handlerOnChange(event) {
		// 	console.log(event);
		// },
		setNormalWordView(event) {
			event.preventDefault();
			event.stopPropagation();
			this.showNormalWordView = !this.showNormalWordView;
		},
		selectEmoji(event) {
			event.preventDefault();
			event.stopPropagation();
			this.showEmoji = !this.showEmoji;
		},
		sendMessageText() {
			const messageContent = document.getElementById('widget-message-text').innerHTML;
			if (!ZcoIM.agent) {
				this.$zcoMessage({
					type: 'error',
					message: `${this.$t('no-calls')}`,
					duration: 3
				});
				return;
			}
			if (messageContent == '') {
				this.$zcoMessage({
					type: 'error',
					message: `${this.$t('enter-content')}`,
					duration: 3
				});
				document.getElementById('widget-message-text').focus();
				return;
			}
			// let content = Emoji.imgFace2textFace(
			// 	messageContent
			// 		.replace(/<br>/gi, '\n')
			// 		.replace(/<div>/gi, '\n')
			// 		.replace(/&nbsp;/gi, ' ')
			// 		.replace(/<span>/gi, '')
			// 		.replace(/<\/span>/gi, '')
			// );
			const data = sendMessageToRecord('text', messageContent, ZcoIM.agent, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitTextMessage(data);
			document.getElementById('widget-message-text').innerHTML = '';
			if (this.showEmoji) {
				this.showEmoji = false;
			}
		},

		sendImage(event) {
			const file = document.getElementById('imgfile').files[0];
			let imgTest = ['png', 'jpg', 'jpeg', 'gif'];
			let index = file.name.lastIndexOf('.');
			let ext = file.name.substr(index + 1).toLowerCase();
			if (imgTest.indexOf(ext) === -1) {
				this.$zcoMessage({
					type: 'error',
					message: `${this.$t('image-not-support')}`,
					duration: 3
				});
				event.target.value = null;
				return;
			}
			if (file.size > ZcoIM.maxUploadFileSize) {
				this.$zcoMessage({
					type: 'error',
					message: `${this.$t('file-limit-500-kbs')}`,
					duration: 3
				});
				event.target.value = null;
				return;
			}
			let URL = window.URL || window.webkitURL;
			let imgURL = URL.createObjectURL(file);
			console.log('zco-im-web-sendImg-imgURL:', imgURL, new Date());
			let msgData = {};
			msgData.url = imgURL;
			msgData.type = 'pic';
			msgData.name = file.name;
			msgData.file = file;
			const data = sendMessageToRecord('link', msgData, ZcoIM.agent, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitResourceMessage(data);
			event.target.value = null;
		},

		sendFile(event) {
			let file = document.getElementById('docfile').files[0];
			if (file.size > ZcoIM.maxUploadFileSize) {
				this.$zcoMessage({
					type: 'error',
					message: `${this.$t('file-limit-500-kbs')}`,
					duration: 3
				});
				event.target.value = null;
				return;
			}
			let URL = window.URL || window.webkitURL;
			let fileURL = URL.createObjectURL(file);
			console.log('zco-im-sendFile-fileURL:', fileURL, new Date());
			let msgData = {};
			msgData.url = fileURL;
			msgData.type = 'doc';
			msgData.name = file.name;
			msgData.file = file;
			msgData.suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
			const data = sendMessageToRecord('link', msgData, ZcoIM.agent, 'in-progress');
			ZcoIM.setChatMessage(data);
			zcoIMEvent.emitResourceMessage(data);
			event.target.value = null;
		},
		handleKnowledgeBase() {
			zcoIMEvent.emitKbButtonClick();
		}
	}
};
</script>

<style scoped>
.web-footer-container {
	width: 100%;
	border-top: 1px solid #e8e8e8;
	position: absolute;
	bottom: 0;
	background: #ffff;
}
.web-footer-header {
	margin: 14px 16px 14px 0;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.send-btn-box button {
	border: 0;
	width: 74px;
	height: 28px;
	background: #252b48;
	border-radius: 2px;
	font-size: 14px;
	color: #ffffff;
}
.send-btn-box button span {
	margin-right: 15px;
}
.send-btn-box {
	position: relative;
}
.send-btn-box button img {
	width: 10px;
	position: absolute;
	top: 12px;
	right: 10px;
}
.web-footer-tool-box img {
	margin: 0 10px;
}
.web-footer-tool-box {
	display: flex;
	/* padding-left: 16px; */
}
.web-chat-window-footer {
	padding: 0 16px;
}
.widget-message-text {
	height: 72px;
	outline: none;
	resize: none;
	border: 0;
	font-size: 12px;
	overflow: auto;
	/* 解决ipad上无法显示光标的问题*/
	-webkit-user-select: auto !important;
	-khtml-user-select: auto !important;
	-moz-user-select: auto !important;
	-ms-user-select: auto !important;
	-o-user-select: auto !important;
	user-select: auto !important;
}
.widget-message-text[contenteditable]:empty:before {
	content: attr(placeholder);
	color: #cccccc;
}
.widget-message-text[contenteditable]:focus {
	content: none;
}
.widget-message-text img {
	margin: 0 4px;
}
/* 设置滚动条的样式 */
::-webkit-scrollbar {
	width: 6px;
}
/* 滚动槽 */
::-webkit-scrollbar-track {
	-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
	border-radius: 10px;
}
/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
	border-radius: 10px;
	background: rgba(0, 0, 0, 0.1);
	-webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
	background: #dddfe1;
}
.emoji-wrapper {
	position: absolute;
	bottom: 150px;
	background: #fff;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.14);
	border-radius: 4px;
	left: 50%;
	transform: translateX(-50%);
}
.emoji-wrapper .emoji-content {
	max-height: 320px;
}
</style>
